import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';

import 'package:sow_app_core/sow_app_core.dart';
import 'package:sow_app_i18n/sow_app_i18n.dart';

import '../../util/ajax_client/ajax_client.dart';
import 'model/ajax_response_model.dart';

class AjaxRestClient implements RestClient {
  AjaxClient client = AjaxClient();
  String _authorization = "";
  String _host = I18n.backend_ip;
  int _port = I18n.backend_port;

  @override
  int get port => _port;
  @override
  String get host => _host;
  @override
  String get authorization => _authorization;

  final Map<String, String> _headers = {};
  @override
  setAuthorization(value) {
    _authorization = value;
  }

  @override
  setHostEnv(String host, int port) {
    _host = host;
    _port = port;
  }

  @override
  Future<AjaxResponseModel> invokeHttp(String path, RequestType type,
      {String? contentType, dynamic body}) async {
    _headers['Authorization'] = _authorization;

    AjaxResponseModel model;
    try {
      final json = jsonDecode(utf8.decode((await client.invoke(
              Uri(scheme: 'http', host: _host, port: _port).replace(path: path),
              type,
              headers: _headers,
              body: body,
              contentType: contentType))
          .bodyBytes));
      model = AjaxResponseModel.fromJson(json);
      if (model.code != 200) {
        // ignore: avoid_print
        print(model.msg);
        throw ServerException(model.msg);
      }
    } on ServerException {
      rethrow;
    } catch (e, trace) {
      // ignore: avoid_print
      print(e);
      // ignore: avoid_print
      print(trace);
      throw ServerException(I18n.server_response_error);
    }
    return model;
  }

  @override
  Future<Uint8List> getFile(String path) async => (await client.invoke(
          Uri(scheme: 'http', host: _host, port: _port).replace(path: path),
          headers: _headers,
          RequestType.get))
      .bodyBytes;
}
